package com.csdj.controller;

/**
 * Author : 今晚几点睡_Ada
 * Date: 2022/9/7
 * Time: 11:30
 * 注:
 */

import com.csdj.exception.*;
import com.csdj.pojo.TUser;
import com.csdj.utils.JsonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;

/**
 * 控制器基类
 */
public class BaseController {
    //状态码 默认成功200
    public static final Integer ok=200;

    /**
     * @ExceptionHandler用于统一处理方法抛出的异常
     * @param e
     * @return
     */
    @ExceptionHandler(ServiceException.class)
    public JsonResult<Void> handleException(Throwable e) {
        JsonResult<Void> result = new JsonResult<Void>(e);
        if (e instanceof UsernameDuplicateException) {
            result.setCode(400);
        } else if (e instanceof InsertException) {
            result.setCode(500);
        }else if (e instanceof PasswordNotMatchException){
            result.setCode(401);
        }else if (e instanceof UserNotFoundException){
            result.setCode(402);
        }
        return result;
    }
    /**
     * 从HttpSession对象中获取uid
     * @param session HttpSession对象
     * @return 当前登录的用户的id
     */
    protected final Integer getUidFromSession(HttpSession session) {
        TUser loginUser = (TUser)session.getAttribute("LoginUser");
        return loginUser.getUid();
    }

    /**
     * 从HttpSession对象中获取用户名
     * @param session HttpSession对象
     * @return 当前登录的用户名
     */
    protected final String getUsernameFromSession(HttpSession session) {
        TUser loginUser = (TUser)session.getAttribute("LoginUser");
        return loginUser.getUsername();
    }
}
